<template>
  <el-dialog :title="title" :visible="showDialog" @close="closeDialog">
    <el-form :model="form" ref="fromRef" :rules="rules" label="180">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model.trim="form.name" placeholder="角色名称"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model.trim="form.description" placeholder="角色名称"></el-input>
      </el-form-item>
    </el-form>
    <el-row slot="footer">
      <el-col :span="24">
        <el-button size="small" @click="closeDialog">取 消</el-button>
        <el-button size="small" type="primary" @click="handleConfirm"
          >确 定</el-button
        >
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
export default {
  props: {
    roleList: {
      type: Array,
      default: () => [],
    },
    showDialog:{
        type:Boolean,
        default:false
    },
    title:{
        type:String
    }
  },
  data() {
    const validateName = (rule, value, callback) => {
      const isRepeat = this.roleList.some((item) => {
        if (this.form.id) {
          //编辑校验
          return item.name === value && item.id !== this.form.id;
        } else {
          return item.name === value;
        }
      });
      isRepeat ? callback(new Error('角色名重复')) :  callback()
    };

    return {
      form: {
        name: "",
        description: "",
      },
      rules: {
        name: [
          { required: true, message: "角色名不能为空", trigger: "blur" },
          { validator: validateName, trigger: "blur" },
        ],
        description: [
          { required: true, message: "角色描述不能为空", trigger: "blur" },
        ],
      },
    };
  },
  methods: {

   
    //确认
    handleConfirm() {
        this.$refs.fromRef.validate(valid=>{
            if(valid){
                this.$emit('submit',this.form)
            }
        })
    },
    //关闭弹窗
    closeDialog(){
        this.$emit('update:showDialog',false)
        this.form = this.$options.data().form; 
    },
    
  },
};
</script>

<style>
</style>